/**
 * @Company: 小明
 * @Author: 40313
 * @DATE: 2020/12/19 星期六 上午 10:48
 */
package com.situ.oa.index.controller;

import com.situ.oa.index.service.IndexService;
import com.situ.oa.util.ConfigUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * ClassName: IndexController
 *
 * @Author: 40313
 * @Description:(登录及进管理系统首页)
 */
@Controller
public class IndexController {
    private IndexService indexService;

    @Autowired
    public IndexController(IndexService indexService) {
        this.indexService = indexService;
    }

    /**
     * @param modelAndView
     * @return 进登录页面
     */
    @RequestMapping({"/", "/login"})
    public ModelAndView goLogin(ModelAndView modelAndView) {
        modelAndView.setViewName("login");
        return modelAndView;
    }

    /**
     * #执行登录校验
     *
     * @param userCode
     * @param userPass
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @PostMapping("/dologin")
    public Integer doLogin(String userCode, String userPass, String autologin, HttpServletRequest request, HttpServletResponse response) {
        return indexService.doUserLogin(userCode, userPass, autologin, request, response);
    }

    @GetMapping("/index")
    public ModelAndView goIndex(ModelAndView modelAndView, HttpSession session, HttpServletRequest request) {
        indexService.checkAutoLogin(request);
        if (session.getAttribute(ConfigUtil.SESSION_LOGIN_USER_NAME) == null) {
            modelAndView.setViewName("login");
        } else {
            modelAndView.setViewName("index");
        }
        return modelAndView;
    }

    /**
     * @param session
     * @return
     * @Title: doLoginOut
     * @Description:(执行退出)
     */
    @ResponseBody
    @RequestMapping("/dologinout")
    public Integer doLoginOut(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (ConfigUtil.COOKIE_NAME.equals(cookie.getName())) {
                cookie.setMaxAge(0);
                response.addCookie(cookie);
                break;
            }
        }
        session.removeAttribute(ConfigUtil.SESSION_LOGIN_USER_NAME);
        return 1;
    }
}
